#!/bin/bash
# name: check.sh
# description: System Health Check

# CPU idle less than 10%
CPU_P=10
# Swap uses more than 30%
SWAP_F=30

RED="\e[1;31m"
GREEN="\e[1;32m"
RESET="\e[0m"

system_check() {
    # hostname
    echo -e "\nHostname: $GREEN$(hostname)$RESET"

    # IPaddress
    echo -e "IPaddress: $GREEN$(/sbin/ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:")$RESET"

    # CPU idle less than 10%
    if [ $(vmstat 1 5 | tail -1 | awk '{print $15}') -lt $CPU_P ]; then
        echo -e "Processor: CPU idle less than $RED 10% $RESET"
    else
        echo -e "Processor: CPU idle less than $GREEN $(vmstat 1 3 | tail -1 | awk '{print $15}')% $RESET"
    fi

    # Swap uses more than 30%
    if [ $(free -m | grep Swap | awk '{printf "%d\n",$3/$2*100}') -gt $SWAP_F ]; then
        echo -e "Exchange space: Swap uses more than $RED $(free -m | grep Swap | awk '{printf "%d\n",$3/$2*100}')% $RESET \n"
        free -m | grep -Ei "total|swap"
    else
        echo -e "Exchange space: Swap uses less than $RED 30% $RESET \n"
    fi

    # File system uses more than 80%
    i=0
    for m in $(df -h | grep "^/dev" | awk 'sub("%","",$5) {if ($5/80 > 1) print $6}' | xargs); do
        echo -e "Filesystem: File system uses more than $RED 80% $RESET"
        if [ $i -eq 0 ]; then
            df -h | head -1
            let i=i+1
        fi
        df -h $m | sed '1d'
    done

    # ntpq -p
    echo -e "\n# ntpq -p"
    ntpq -p
    # if [ $? == 0 ]; then
    #     echo -e "ntpq -p $GREEN successful $RESET"
    # else
    #     echo -e "ntpq -p $RED unsuccessful $RESET"
    # fi

    # dmesg log
    if [ -n "$(egrep -i "error|failed" /var/log/dmesg)" ]; then
        echo -e "\n$RED# egrep -i 'error|failed' /var/log/dmesg $RESET"
        egrep -i "error|failed" /var/log/dmesg
    fi

    # messages log
    if [ -n "$(egrep -i "error|failed" /var/log/messages)" ]; then
        echo -e "\n$RED# egrep -i 'error|failed' /var/log/messages $RESET"
        egrep -i "error|failed" /var/log/messages
    fi
}

echo -e "\nThe system check start Time : $(date +'%F %T')"

system_check

echo -e "\nThe system check end Time : $(date +'%F %T')\n"
